package com.kc.business.service.impl;

import com.kc.business.domain.*;
import com.kc.business.mapper.*;
import com.kc.business.service.IBizScenicEnterService;
import com.kc.common.config.TicketConfig;
import com.kc.common.constant.BizConstants;
import com.kc.common.constant.UserConstants;
import com.kc.common.core.domain.entity.SysRole;
import com.kc.common.core.domain.entity.SysUser;
import com.kc.common.exception.CustomException;
import com.kc.common.model.KcTicketResult;
import com.kc.common.utils.SecurityUtils;
import com.kc.common.utils.TicketUtil;
import com.kc.system.domain.SysUserRole;
import com.kc.system.mapper.SysRoleMapper;
import com.kc.system.mapper.SysUserMapper;
import com.kc.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author zhangshuo
 * @version 1.0
 * @date 2020/9/15
 */
@Service
@Slf4j
public class BizScenicEntryServiceImpl implements IBizScenicEnterService {

    @Resource
    BizScenicEnterMapper bizScenicEnterMapper;
    @Resource
    SysRoleMapper sysRoleMapper;
    @Resource
    BizRoleMapper bizRoleMapper;
    @Resource
    BizUserRoleMapper bizUserRoleMapper;
    @Resource
    BizScenicMapper bizScenicMapper;
    @Resource
    BizUserMapper bizUserMapper;
    @Resource
    SysUserMapper adminMapper;
    @Resource
    SysUserRoleMapper sysUserRoleMapper;
    @Resource
    TicketUtil ticketUtil;
    @Resource
    TicketConfig ticketConfig;

    /**
     * 审核通过
     */
    public static final String PASS = "1";
    /**
     * 用户是景区
     */
    public static final Integer IS_SCENIC = 1;

    /**
     * 景区入驻列表
     *
     * @param bizScenicEnterForm
     * @return
     */
    @Override
    public List<BizScenicEnterForm> getList(BizScenicEnterForm bizScenicEnterForm) {
        return bizScenicEnterMapper.select(bizScenicEnterForm);
    }

    /**
     * 新增景区入驻申请
     *
     * @param bizScenicEnterForm
     * @return
     */
    @Override
    public int add(BizScenicEnterForm bizScenicEnterForm) {
        return bizScenicEnterMapper.insertSelective(bizScenicEnterForm);
    }

    /**
     * 修改景区入驻申请
     *
     * @param bizScenicEnterForm
     * @return
     */
    @Override
    @Transactional
    public int edit(BizScenicEnterForm bizScenicEnterForm) {
        //通过审核
        if (BizConstants.PASS_VERIFY.equals(bizScenicEnterForm.getStatus())) {
            BizScenicEnterForm enterForm = bizScenicEnterMapper.selectByPrimaryKey(bizScenicEnterForm.getEnterId());
            //APP用户id
            int useId = enterForm.getUserId();

            //更新APP用户
            BizUser bizUser = bizUserMapper.selectByPrimaryKey(useId);
            bizUser.setIsScenic(BizConstants.YES);
            //景区默认一级分销
            bizUser.setIsAgent(1);
            bizUserMapper.updateByPrimaryKeySelective(bizUser);
            //给景区开通分销中心
            BizRole bizDistributionRole = bizRoleMapper.getActiveByRoleKey(UserConstants.ROLE_DISTRIBUTION_APP);
            if(bizDistributionRole != null){
                BizUserRole bizUserRole = new BizUserRole();
                bizUserRole.setCreateTime(new Date());
                bizUserRole.setUserId(useId);
                bizUserRole.setRoleId(bizDistributionRole.getId());
                bizUserRoleMapper.insert(bizUserRole);
            }

            //票务系统同步数据
            Map<String,String> map = new HashMap<>();
            map.put("Name",enterForm.getScenicName());
            map.put("MaxNum","1");
            Map<String,String> mapSort = ticketUtil.ascMap(map);
            log.info("[查询景区门票详情]参数数据:{}",map);
            String param = ticketUtil.getRaramString(mapSort);
            String url = ticketConfig.getUrl()+"/Spot/Add";
            KcTicketResult kcTicketResult = ticketUtil.requestTicket(url,param);
            Integer ticketId = Integer.parseInt(kcTicketResult.getData().toString());

            //创建景区
            BizScenic bizScenic = new BizScenic();
            bizScenic.setTenantId(useId);
            bizScenic.setUserId(useId);
            bizScenic.setScenicName(enterForm.getScenicName());
            bizScenic.setLatitude(enterForm.getLatitude());
            bizScenic.setLongitude(enterForm.getLongitude());
            bizScenic.setScenicAddress(enterForm.getScenicAddress());
            bizScenic.setTicketScenicId(ticketId);
            bizScenic.setAdcode(enterForm.getAdcode());
            bizScenic.setCityName(enterForm.getCity());
            bizScenic.setStatus("1");
            bizScenicMapper.insertSelective(bizScenic);

            //创建景区PC端账号
            SysUser admin = new SysUser();
            admin.setNickName(enterForm.getScenicName());
            admin.setPhonenumber(bizUser.getMobile());
            admin.setUserName(bizUser.getMobile());
            if (UserConstants.NOT_UNIQUE.equals(adminMapper.checkUserNameUnique(admin.getUserName()) > 0 ? "1" : "0")) {
                admin = adminMapper.selectUserByUserName(admin.getUserName());
            } else {
                //身份证后6位做密码
                String idCard = enterForm.getIdCard();
                String password = idCard.substring(idCard.length() - 6, idCard.length());
                admin.setPassword(SecurityUtils.encryptPassword(password));
                admin.setTenantId(enterForm.getUserId());
                adminMapper.insertUser(admin);
            }

            //查询PC角色
            SysRole sysRole = sysRoleMapper.checkRoleKeyUnique(UserConstants.ROLE_SCENIC_PC);
            if (sysRole == null) {
                throw new CustomException("请联系管理员，创建PC角色");
            }
            //设置后台用户角色
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(admin.getUserId());
            userRole.setRoleId(sysRole.getRoleId());

            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            list.add(userRole);
            sysUserRoleMapper.batchUserRole(list);

            //查询APP角色
            BizRole appRole = bizRoleMapper.getActiveByRoleKey(UserConstants.ROLE_SCENIC_APP);
            if (appRole == null) {
                throw new CustomException("请联系管理员，创建APP角色");
            }

            //设置APP用户角色
            BizUserRole bizUserRole = new BizUserRole();
            bizUserRole.setUserId(bizUser.getId());
            bizUserRole.setRoleId(appRole.getId());
            bizUserRoleMapper.insert(bizUserRole);
        }

        return bizScenicEnterMapper.updateByPrimaryKeySelective(bizScenicEnterForm);
    }
}
